<template>
  <div class='container app-container'>

    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>试题录入</span>
      </div>
      <el-form ref="form" :model="questionForm" :rules="formRules" label-width="120px">
        <el-form-item label="学科：" prop="subjectID">
          <el-select v-model="questionForm.subjectID" placeholder="请选择" @change="changeSubject">
            <el-option
              v-for="item in subjectList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="目录：" prop="catalogID">
          <el-select v-model="questionForm.catalogID" placeholder="请选择">
            <el-option
              v-for="item in directoryList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="企业：" prop="enterpriseID">
          <el-select v-model="questionForm.enterpriseID" placeholder="请选择">
            <el-option
              v-for="item in companyList"
              :key="item.id"
              :label="item.company"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="城市：" prop="province">
          <div style="width: 400px;">
            <el-select v-model="questionForm.province" class="city-select" placeholder="请选择" style="margin-right: 2%;"
                       @change="cityChange">
              <el-option
                v-for="item in cityList"
                :key="item"
                :value="item"
              />
            </el-select>
            <el-select v-model="questionForm.city" class="city-select" placeholder="请选择">
              <el-option
                v-for="item in areaList"
                :key="item"
                :value="item"
              />
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="方向：" prop="direction">
          <el-select v-model="questionForm.direction" placeholder="请选择">
            <el-option value="o2o"></el-option>
            <el-option value="外包服务"></el-option>
            <el-option value="企业服务"></el-option>
            <el-option value="互联网金融"></el-option>
            <el-option value="企业咨询"></el-option>
            <el-option value="互联网"></el-option>
            <el-option value="电子商务"></el-option>
            <el-option value="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题型：" prop="questionType">
          <el-radio-group v-model="questionForm.questionType" @change="changeRadio">
            <el-radio label="1">单选</el-radio>
            <el-radio label="2">多选</el-radio>
            <el-radio label="3">简答</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="难度：" prop="difficulty">
          <el-radio-group v-model="questionForm.difficulty">
            <el-radio label="1">简单</el-radio>
            <el-radio label="2">一般</el-radio>
            <el-radio label="3">困难</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="题干：" prop="question">
          <quill-editor
            v-model="questionForm.question"
            :options="editorOption"
            @blur="questionBlur"
          >
          </quill-editor>
        </el-form-item>
        <el-form-item v-show="!(questionForm.questionType==='3')" label="选项：">
          <div v-show="questionForm.questionType==='1'">
            <div v-for="(item,i) in optionsData" :key="item.id" class="Options" style="padding: 8px 0;">
              <el-radio-group v-model="radioValue" @change="changeOptionsRadio">
                <el-radio :label=i>
                  {{ item.code + '：' }}
                </el-radio>
              </el-radio-group>
              <el-input v-model="item.title" style="width: 240px;"/>
              <upload-image ref="uploadImg" @on-success="item.img=$event"/>
            </div>
          </div>
          <div v-show="questionForm.questionType==='2'">
            <div v-for="item in optionsDataTwo" :key="item.id" class="Options" style="padding: 8px 0;">
              <el-checkbox v-model="item.isRight">
                {{ item.code + '：' }}
              </el-checkbox>
              <el-input v-model="item.title" style="width: 240px;"></el-input>
              <upload-image ref="uploadImg1" @on-success="item.img=$event"/>
            </div>
          </div>
        </el-form-item>
        <el-form-item v-show="!(questionForm.questionType==='3')">
          <el-button :disabled="!(questionForm.questionType==='2')" size="small" type="danger" @click="addOption">
            +增加选项与答案
          </el-button>
        </el-form-item>
        <el-form-item label="解析视频：" prop="videoURL">
          <el-input v-model="questionForm.videoURL" style="width: 400px;"/>
        </el-form-item>
        <el-form-item label="答案解析：" prop="answer">
          <quill-editor
            ref="quill"
            v-model="questionForm.answer"
            :options="editorOption"
            @blur="answerBlur"
          >
          </quill-editor>
        </el-form-item>
        <el-form-item label="题目备注：" prop="remarks">
          <el-input
            v-model="questionForm.remarks"
            :rows="4"
            style="width: 400px;"
            type="textarea"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="标签：">
          <el-select
            v-model="questionForm.tags"
            allow-create
            default-first-option
            filterable
            multiple
            placeholder="请选择">
            <el-option
              v-for="item in tagsList"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item label-width="100px">
          <el-button type="primary" @click="addNewQuestion">确认提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import 'highlight.js/styles/monokai-sublime.css' // 代码高亮样式
import hljs from 'highlight.js'
import { quillEditor } from 'vue-quill-editor'
import { list as companyList } from '@/api/hmmm/companys'
import { subjectsSimple } from '@/api/hmmm/subjects'
import { citys, provinces } from '@/api/hmmm/citys'
import { directorySimple } from '@/api/hmmm/directorys'
import { tagsSimple } from '@/api/hmmm/tags'
import UploadImage from '@/module-hmmm/components/UploadImg'
import { add as questionAdd, detail, update } from '@/api/hmmm/questions'

export default {
  components: { UploadImage, quillEditor },
  data () {
    return {
      rowId: undefined,
      // 富文本
      editorOption: {
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 列表
            ['blockquote'], // 引用，
            ['code-block', 'image', 'link'] // 代码块,上传图片、上传视频
          ],
          syntax: {
            highlight: text => {
              return hljs.highlightAuto(text).value // 这里就是代码高亮需要配置的地方
            }
          }
        }
      },
      questionForm: {
        // 学科列表选择的数据
        subjectID: '',
        // 目录选择的数据
        catalogID: '',
        // 选择的企业数据
        enterpriseID: '',
        // 城市
        province: '',
        // 地区
        city: '',
        // 方向
        direction: '',
        // 题型
        questionType: '1',
        // 难度
        difficulty: '1',
        // 题干
        question: '',
        // 选项
        options: [],
        // 视频url
        videoURL: '',
        // 答案解析
        answer: '',
        // 题目备注
        remarks: '',
        // 标签
        tags: []
      },
      optionsData: [
        { isRight: false, code: 'A', title: '', img: '' },
        { isRight: false, code: 'B', title: '', img: '' },
        { isRight: false, code: 'C', title: '', img: '' },
        { isRight: false, code: 'D', title: '', img: '' }
      ], // 单选题型
      optionsDataTwo: [
        { code: 'A', title: '', img: '', isRight: false },
        { code: 'B', title: '', img: '', isRight: false },
        { code: 'C', title: '', img: '', isRight: false },
        { code: 'D', title: '', img: '', isRight: false }
      ], // 多选数据
      subjectList: [], // 学科类型
      companyList: [], // 企业
      directoryList: [], // 二级目录
      tagsList: [], // 标签列表
      cityList: [], // 城市列表
      areaList: [], // 城市列表
      radioValue: 5, // 单选按钮选中的数据
      ASCII: null, // ASCII 码值
      formRules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        province: [
          { required: true, message: '请选择地区', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        question: [
          { required: true, message: '请输入题干', trigger: 'blur' }
        ],
        remarks: [{ required: true, message: '请填写题目备注', trigger: 'blur' }],
        answer: [{ required: true, message: '请填写答案解析', trigger: 'blur' }],
        videoURL: [{ required: true, message: '请填写解析视频链接', trigger: 'blur' }]
      }

    }
  },
  watch: {
    '$route.query.id': {
      immediate: true,
      handler: async function (newValue, oldValue) {
        this.rowId = newValue
        if (newValue) {
          // 富文本编辑器神坑处理
          this.$nextTick(function () {
            const inputDom = document.querySelectorAll('.el-input__inner')[0]
            inputDom.focus()
          })
          const res = await detail({ id: this.rowId })
          this.questionForm = res.data
          res.data.options.sort((a, b) => {
            return (a.code.charCodeAt() + '') > (b.code.charCodeAt() + '') ? 1 : -1
          })
          res.data.options.forEach((item, index) => {
            if (item.img) {
              this.$nextTick(() => {
                this.$refs.uploadImg[index].fileList.push({ url: item.img })
              })
            }
          })
          res.data.options.forEach((item, index) => {
            if (item.img) {
              this.$nextTick(() => {
                this.$refs.uploadImg1[index].fileList.push({ url: item.img })
              })
            }
          })
          this.questionForm.tags = this.questionForm.tags.split(',')
          if (this.questionForm.questionType === '1') {
            this.radioValue = res.data.options.findIndex(item => item.isRight)
            this.optionsData = res.data.options.map(item => {
              item.isRight = !!item.isRight
              return item
            })
          } else if (this.questionForm.questionType === '2') {
            this.optionsDataTwo = res.data.options.map(item => {
              item.isRight = !!item.isRight
              return item
            })
          }
          await this.$refs.quill.quill.enable(false)
          await this.loadFormList()
          await this.loadDirectorySimple()
          this.cityChange()
        } else {
          Object.assign(this.$data, this.$options.data())
          this.$nextTick(() => {
            this.$refs.form.resetFields()
            const _field = this.$refs.form.fields
            _field.map(i => {
              if (i.prop === 'answer') {
                i.resetField()
                return false
              }
            })
            // this.$refs.form.clearValidate(['answer'])
            this.loadFormList()
          })
        }
      }
    }
  },
  created () {
    this.loadFormList()
  },
  methods: {
    async loadFormList () {
      // 获取学科列表
      const res = await subjectsSimple()
      this.subjectList = res.data
      // 获取企业列表
      const { data } = await companyList({ pagesize: 10000 })
      this.companyList = data.items
      if (!this.companyList.length) {
        this.questionForm.enterpriseID = ''
      }
    },
    // 当学科下拉框发生变化时触发
    changeSubject () {
      this.loadDirectorySimple()
    },
    // 获取二级列表  // 获取标签列表
    async loadDirectorySimple () {
      const res = await directorySimple({ subjectID: this.questionForm.subjectID })
      this.directoryList = res.data
      if (!this.directoryList.length) {
        this.questionForm.catalogID = ''
      }
      const res1 = await tagsSimple({ subjectID: this.questionForm.subjectID })
      this.tagsList = res1.data
      // 获取城市列表
      this.cityList = provinces()
    },
    // 城市
    cityChange () {
      this.areaList = citys(this.questionForm.province)
      this.questionForm.city = this.areaList[0]
    },
    // 题型发生变化
    changeRadio () {
      if (this.questionForm.questionType === '3') {
        return
      }
      if (this.questionForm.questionType === '1') {
        this.radioValue = 5
      }
      if (this.questionForm.questionType === '2') {

      }
    },
    // 选项单选发生变化
    changeOptionsRadio (i) {
      this.optionsData.forEach(item => {
        item.isRight = false
      })
      this.optionsData[i].isRight = true
    },
    // 增加多选项
    addOption () {
      this.ASCII = this.optionsDataTwo[this.optionsDataTwo.length - 1].code.charCodeAt() + 1
      const str = String.fromCharCode(this.ASCII)
      this.optionsDataTwo.push({
        code: str,
        img: '',
        isRight: false,
        title: ''
      })
      this.ASCII++
    },
    // 点击提交
    async addNewQuestion () {
      try {
        await this.$refs.form.validate()
        const data = JSON.parse(JSON.stringify(this.questionForm))
        if (data.questionType === '1') {
          data.options = this.optionsData
        } else if (this.questionForm.questionType === '2') {
          data.options = this.optionsDataTwo
        }
        data.tags = (data.tags && data.tags.join(',')) || ''
        if (this.rowId) {
          await update({ ...data, id: this.rowId - 0 })
          this.$message.success('更新成功')
          await this.$router.back()
        } else {
          await questionAdd(data)
          this.$message.success('添加成功')
          await this.$router.push('/questions/list')
        }
      } catch (e) {
        console.log(e)
        this.$message.error('请填写必填项')
      }
    },
    //  题干失去焦点校验
    questionBlur () {
      this.$refs.form.validateField('question')
    },
    answerBlur () {
      this.$refs.form.validateField('answer')
    }
  }
}
</script>

<style lang='less' scoped>
.app-container {
  /deep/ .el-select {
    width: 400px;
  }

  /deep/ .city-select {
    display: inline-block;
    width: 49%;
  }

  /deep/ .el-radio__label {
    display: inline-block;

    padding-left: 10px;
    line-height: 19px;
    font-size: 14px;
  }

  /deep/ .el-checkbox__label {
    vertical-align: middle;

  }

  .Options {
    display: flex;
    align-items: center;
  }

  /deep/ .ql-editor {
    height: 200px;
  }

  /deep/ .ql-toolbar.ql-snow {
    padding: 0 8px;
  }
}
</style>
